/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2023. All rights reserved.
 *
 */

import fse from 'fs-extra';
import os from 'os';
import path from 'path';

import { logInfo } from './log.js';

let hvigorUserHomeCacheDirHasLogged = false;

/**
 * 获取user home下的.hvigor目录，wapper专用
 *
 */
export function getHvigorUserHomeDir(): string {
  const defaultUserHome = path.resolve(os.homedir(), '.hvigor');
  const hvigorUserHome = process.env.HVIGOR_USER_HOME;

  if (hvigorUserHome === undefined) {
    return defaultUserHome;
  }
  if (!path.isAbsolute(hvigorUserHome)) {
    if (!hvigorUserHomeCacheDirHasLogged) {
      logInfo(`Invalid custom userhome hvigor data dir:${hvigorUserHome}`);
      hvigorUserHomeCacheDirHasLogged = true;
    }
    return defaultUserHome;
  }
  if (fse.existsSync(hvigorUserHome) && fse.statSync(hvigorUserHome).isFile()) {
    logInfo(`File already exists: ${hvigorUserHome}`);
    return defaultUserHome;
  }
  fse.ensureDirSync(hvigorUserHome);
  return hvigorUserHome;
}
